"""
学生个人仪表盘视图
"""
from django.db.models import Count, Q
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from students.models import Student
from resume_management.models import Resume
from interviews.models import Interview
from jobs.models import Job, JobApplication
from .serializers import PersonalizedStatsSerializer


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_statistics(request):
    """获取学生个人统计数据"""
    try:
        user = request.user
        
        # 确保是学生用户
        if user.role != 'student':
            return Response(
                {'error': '此接口仅供学生使用'}, 
                status=status.HTTP_403_FORBIDDEN
            )
        
        try:
            student = Student.objects.get(user=user)
        except Student.DoesNotExist:
            return Response(
                {'error': '学生信息不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )
        
        # 统计个人数据
        resume_count = Resume.objects.filter(student=student).count()
        interview_count = Interview.objects.filter(student=student).count()
        application_count = JobApplication.objects.filter(student=student).count()
        
        # 获取简历完成度
        latest_resume = Resume.objects.filter(student=student).first()
        resume_completion = float(latest_resume.completion_rate) if latest_resume else 0.0
        
        # 统计申请状态
        application_stats = JobApplication.objects.filter(student=student).aggregate(
            pending=Count('id', filter=Q(status='pending')),
            approved=Count('id', filter=Q(status='approved')),
            rejected=Count('id', filter=Q(status='rejected'))
        )
        
        # 统计面试状态
        interview_stats = Interview.objects.filter(student=student).aggregate(
            scheduled=Count('id', filter=Q(status='scheduled')),
            completed=Count('id', filter=Q(status='completed')),
            cancelled=Count('id', filter=Q(status='cancelled'))
        )
        
        data = {
            'resumeCount': resume_count,
            'interviewCount': interview_count,
            'applicationCount': application_count,
            'resumeCompletion': resume_completion,
            'applicationStats': application_stats,
            'interviewStats': interview_stats,
            'employmentStatus': student.employment_status,
            'profileCompletion': calculate_profile_completion(student)
        }
        
        return Response(data)
        
    except Exception as e:
        return Response(
            {'error': f'获取个人统计失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_resume_progress(request):
    """获取学生简历进度"""
    try:
        user = request.user

        # 检查用户角色
        if user.role != 'student':
            return Response(
                {'error': '此接口仅供学生使用'},
                status=status.HTTP_403_FORBIDDEN
            )

        # 获取学生信息
        try:
            student = Student.objects.get(user=user)
        except Student.DoesNotExist:
            return Response(
                {'error': '学生信息不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

        # 获取学生的所有简历
        resumes = Resume.objects.filter(student=student).order_by('-updated_at')

        resume_data = []
        for resume in resumes:
            try:
                # 确保completion_rate有值
                completion_rate = float(resume.completion_rate) if resume.completion_rate else 0.0

                # 如果completion_rate为0，尝试重新计算
                if completion_rate == 0.0:
                    completion_rate = resume.calculate_actual_completion_rate()

                resume_info = {
                    'id': resume.id,
                    'title': resume.title,
                    'status': resume.status,
                    'resume_type': resume.resume_type,
                    'completion_rate': completion_rate,
                    'created_at': resume.created_at.isoformat() if resume.created_at else None,
                    'updated_at': resume.updated_at.isoformat() if resume.updated_at else None,
                }

                # 安全地调用方法
                try:
                    resume_info['can_edit'] = resume.can_edit()
                except:
                    resume_info['can_edit'] = True

                try:
                    resume_info['can_submit'] = resume.can_submit_for_review()
                except:
                    resume_info['can_submit'] = completion_rate >= 80

                resume_data.append(resume_info)

            except Exception as e:
                print(f"处理简历 {resume.id} 时出错: {e}")
                # 添加基础信息，避免整个API失败
                resume_data.append({
                    'id': resume.id,
                    'title': resume.title,
                    'status': resume.status,
                    'resume_type': getattr(resume, 'resume_type', 'online'),
                    'completion_rate': 0.0,
                    'created_at': resume.created_at.isoformat() if resume.created_at else None,
                    'updated_at': resume.updated_at.isoformat() if resume.updated_at else None,
                    'can_edit': True,
                    'can_submit': False
                })

        # 计算总体进度
        total_completion = 0
        if resume_data:
            total_completion = sum(r['completion_rate'] for r in resume_data) / len(resume_data)

        data = {
            'resumes': resume_data,
            'total_resumes': len(resume_data),
            'average_completion': round(total_completion, 2),
            'latest_resume': resume_data[0] if resume_data else None,
            'student_info': {
                'id': student.id,
                'name': student.name,
                'student_id': student.student_id
            }
        }

        return Response(data)

    except Exception as e:
        print(f"my_resume_progress API错误: {e}")
        return Response(
            {'error': f'获取简历进度失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_interview_history(request):
    """获取学生面试历史"""
    try:
        user = request.user
        
        if user.role != 'student':
            return Response(
                {'error': '此接口仅供学生使用'}, 
                status=status.HTTP_403_FORBIDDEN
            )
        
        try:
            student = Student.objects.get(user=user)
        except Student.DoesNotExist:
            return Response(
                {'error': '学生信息不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )
        
        # 获取面试历史
        interviews = Interview.objects.filter(student=student).order_by('-created_at')
        
        interview_data = []
        for interview in interviews:
            interview_data.append({
                'id': interview.id,
                'title': interview.title,
                'interview_type': interview.interview_type,
                'scheduled_time': interview.scheduled_time,
                'status': interview.status,
                'location': interview.location,
                'feedback': interview.feedback,
                'created_at': interview.created_at
            })
        
        # 统计面试结果
        stats = {
            'total': len(interview_data),
            'completed': len([i for i in interview_data if i['status'] == 'completed']),
            'scheduled': len([i for i in interview_data if i['status'] == 'scheduled']),
            'cancelled': len([i for i in interview_data if i['status'] == 'cancelled'])
        }
        
        data = {
            'interviews': interview_data,
            'statistics': stats,
            'success_rate': round((stats['completed'] / stats['total']) * 100, 2) if stats['total'] > 0 else 0
        }
        
        return Response(data)
        
    except Exception as e:
        return Response(
            {'error': f'获取面试历史失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_applications_status(request):
    """获取学生申请状态"""
    try:
        user = request.user
        
        if user.role != 'student':
            return Response(
                {'error': '此接口仅供学生使用'}, 
                status=status.HTTP_403_FORBIDDEN
            )
        
        try:
            student = Student.objects.get(user=user)
        except Student.DoesNotExist:
            return Response(
                {'error': '学生信息不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )
        
        # 获取申请状态
        applications = JobApplication.objects.filter(student=student).order_by('-applied_at')
        
        application_data = []
        for app in applications:
            application_data.append({
                'id': app.id,
                'job_title': app.job.title if app.job else '未知岗位',
                'company_name': app.job.company.name if app.job and app.job.company else '未知公司',
                'status': app.status,
                'applied_date': app.applied_at,
                'cover_letter': app.cover_letter,
                'resume_file': app.resume_file.url if app.resume_file else None
            })
        
        # 统计申请状态
        stats = JobApplication.objects.filter(student=student).aggregate(
            total=Count('id'),
            pending=Count('id', filter=Q(status='pending')),
            approved=Count('id', filter=Q(status='approved')),
            rejected=Count('id', filter=Q(status='rejected'))
        )
        
        data = {
            'applications': application_data,
            'statistics': stats,
            'success_rate': round((stats['approved'] / stats['total']) * 100, 2) if stats['total'] > 0 else 0
        }
        
        return Response(data)
        
    except Exception as e:
        return Response(
            {'error': f'获取申请状态失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def job_recommendations(request):
    """获取推荐岗位"""
    try:
        user = request.user
        limit = int(request.GET.get('limit', 10))
        
        if user.role != 'student':
            return Response(
                {'error': '此接口仅供学生使用'}, 
                status=status.HTTP_403_FORBIDDEN
            )
        
        try:
            student = Student.objects.get(user=user)
        except Student.DoesNotExist:
            return Response(
                {'error': '学生信息不存在'}, 
                status=status.HTTP_404_NOT_FOUND
            )
        
        # 简单的推荐算法：基于学生专业和已申请的岗位
        # 获取学生专业信息
        student_grade = getattr(student, 'grade', None)
        
        # 获取已申请的岗位ID
        applied_job_ids = JobApplication.objects.filter(student=student).values_list('job_id', flat=True)
        
        # 推荐岗位：排除已申请的，优先推荐相关专业的
        recommended_jobs = Job.objects.filter(
            status='published'
        ).exclude(
            id__in=applied_job_ids
        ).order_by('-created_at')[:limit]
        
        job_data = []
        for job in recommended_jobs:
            job_data.append({
                'id': job.id,
                'title': job.title,
                'company_name': job.company.name if job.company else '未知公司',
                'work_location': job.work_location,
                'salary_range': job.salary_range,
                'job_type': job.job_type,
                'work_mode': job.work_mode,
                'requirements': job.requirements,
                'created_at': job.created_at,
                'match_score': calculate_match_score(student, job)
            })
        
        # 按匹配度排序
        job_data.sort(key=lambda x: x['match_score'], reverse=True)
        
        data = {
            'recommendations': job_data,
            'total': len(job_data),
            'criteria': {
                'grade': student_grade.name if student_grade else None,
                'excluded_applied': len(applied_job_ids)
            }
        }
        
        return Response(data)
        
    except Exception as e:
        return Response(
            {'error': f'获取推荐岗位失败: {str(e)}'}, 
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


# 辅助函数
def calculate_profile_completion(student):
    """计算学生档案完成度"""
    completion_score = 0
    total_fields = 10
    
    # 检查基本信息
    if student.name:
        completion_score += 1
    if student.phone:
        completion_score += 1
    if student.email:
        completion_score += 1
    if student.student_id:
        completion_score += 1
    if student.gender:
        completion_score += 1
    
    # 检查学籍信息
    if hasattr(student, 'grade') and student.grade:
        completion_score += 2
    
    # 检查就业状态
    if student.employment_status:
        completion_score += 1
    
    # 检查是否有简历
    if Resume.objects.filter(student=student).exists():
        completion_score += 1
    
    # 检查头像等其他信息
    if hasattr(student, 'avatar') and student.avatar:
        completion_score += 1
    
    return round((completion_score / total_fields) * 100, 2)


def calculate_match_score(student, job):
    """计算岗位匹配度"""
    score = 0
    
    # 基于年级匹配（简化处理）
    if hasattr(student, 'grade') and student.grade:
        student_grade = student.grade
        if student_grade and student_grade.name.lower() in job.title.lower():
            score += 20
        if student_grade and student_grade.name.lower() in job.requirements.lower():
            score += 15
    
    # 基于工作地点（如果学生有地址信息）
    if hasattr(student, 'address') and student.address:
        if student.address in job.work_location:
            score += 15
    
    # 基于岗位热度（申请人数少的岗位优先推荐）
    application_count = JobApplication.objects.filter(job=job).count()
    if application_count < 5:
        score += 10
    elif application_count < 10:
        score += 5
    
    # 基于发布时间（新岗位优先）
    from django.utils import timezone
    days_since_published = (timezone.now() - job.created_at).days
    if days_since_published <= 7:
        score += 15
    elif days_since_published <= 30:
        score += 10
    
    return min(score, 100)  # 最高100分
